<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getExpress } from '@/api/pointRecord/pointRecord.js';

const expressInfo = ref(null);
const orderInfo = ref(null); // 新增：存储订单详细信息
const orderId = ref(null);
const markers = ref([]); // 地图标记点
const polyline = ref([]); // 轨迹线
const mapKey = 'YRPBZ-FCL6W-PJ3RP-Y3MB5-DBHNQ-WHFBW';

// 地址转经纬度
async function geocode(address) {
  if (!address) return null;
  try {
    const res = await uni.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1`,
      method: 'GET',
      data: {
        address,
        key: mapKey
      }
    });
    if (res.data && res.data.status === 0) {
      return res.data.result.location;
    }
  } catch (e) {}
  return null;
}

// 从context中提取送达地址
function extractDeliveryAddress(context) {
  if (!context) return null;

  // 匹配【送达地址】或【xxxx店】等模式
  const patterns = [
    /送达【([^】]+)】/,
    /【([^】]*店[^】]*)】/,
    /【([^】]*网点[^】]*)】/,
    /【([^】]*代理点[^】]*)】/,
    /【([^】]*驿站[^】]*)】/
  ];

  for (const pattern of patterns) {
    const match = context.match(pattern);
    if (match && match[1]) {
      return match[1];
    }
  }

  return null;
}

onLoad(async (options) => {
  orderId.value = options.id || null;
  if (!orderId.value) return;

  // 获取物流信息
  const res = await getExpress(orderId.value);
  if (res.code === 200) {
    // 处理物流跟踪数据
    if (res.data && Array.isArray(res.data.data)) {
      expressInfo.value = res.data;
    }

    // 处理订单详细信息（包含准确的送达地址）
    if (res.rows && res.rows.length > 0) {
      orderInfo.value = res.rows[0];
    }

    // 如果有物流跟踪数据，解析轨迹点经纬度
    if (expressInfo.value && Array.isArray(expressInfo.value.data)) {
      const traces = expressInfo.value.data;
      const markerArr = [];
      const points = [];
      let markerIdx = 1;

      // 1. 先处理所有轨迹点
      for (let i = 0; i < traces.length; i++) {
        const trace = traces[i];
        let addressToGeocode = null;

        // 对于第一个记录（最新状态），如果是送达状态且有准确的送达地址，优先使用
        if (i === 0 && orderInfo.value && orderInfo.value.deliveryAddress &&
            (trace.status === '派件' || trace.context.includes('送达'))) {
          addressToGeocode = orderInfo.value.deliveryAddress;
        }
        // 如果areaName存在，使用areaName
        else if (trace.areaName) {
          addressToGeocode = trace.areaName;
        }
        // 如果areaName为null，从context中提取送达地址
        else {
          const deliveryAddress = extractDeliveryAddress(trace.context);
          if (deliveryAddress) {
            addressToGeocode = deliveryAddress;
          }
        }

        if (!addressToGeocode) continue; // 跳过无法获取地址的轨迹

        const loc = await geocode(addressToGeocode);
        if (loc) {
          markerArr.push({
            id: i,
            latitude: loc.lat,
            longitude: loc.lng,
            width: 32,
            height: 32,
            // 不使用自定义图标，使用默认标记点
          });
          points.push({ latitude: loc.lat, longitude: loc.lng });
          markerIdx++;
        }
      }

      // 2. 最后加上终点 deliveryAddress
      if (orderInfo.value && orderInfo.value.deliveryAddress) {
        const deliveryLoc = await geocode(orderInfo.value.deliveryAddress);
        if (deliveryLoc) {
          markerArr.push({
            id: 'delivery',
            latitude: deliveryLoc.lat,
            longitude: deliveryLoc.lng,
            width: 32,
            height: 32,
            // 可自定义终点 marker 样式
          });
          points.push({ latitude: deliveryLoc.lat, longitude: deliveryLoc.lng });
        }
      }

      markers.value = markerArr;
      if (points.length > 1) {
        // 反转点的顺序，让箭头指向正确方向（从起点到终点）
        const reversedPoints = [...points].reverse();
        polyline.value = [{
          points: reversedPoints,
          color: '#6366f1',
          width: 4,
          arrowLine: true,
          borderColor: '#4f46e5',
          borderWidth: 1
        }];
      }
    }
  }
});

// 获取状态颜色
function getStatusColor(state) {
  const statusMap = {
    '在途中': '#3b82f6',
    '派送中': '#f59e0b',
    '已签收': '#10b981',
    '问题件': '#ef4444'
  };
  return statusMap[state] || '#6b7280';
}

// 获取状态图标
function getStatusIcon(state) {
  const iconMap = {
    '在途中': '🚚',
    '派送中': '📦',
    '已签收': '✅',
    '问题件': '⚠️'
  };
  return iconMap[state] || '📋';
}
</script>

<template>
  <view class="express-wrap">
    <!-- 顶部状态卡片 -->
    <view v-if="expressInfo" class="status-card">
      <view class="status-header">
        <view class="status-icon">{{ getStatusIcon(expressInfo.state) }}</view>
        <view class="status-text">
          <text class="status-title">{{ expressInfo.state }}</text>
          <text class="status-subtitle">{{ expressInfo.com }}</text>
        </view>
      </view>
      <view class="express-number">运单号：{{ expressInfo.nu }}</view>
      <!-- 显示准确的送达地址 -->
      <view v-if="orderInfo && orderInfo.deliveryAddress" class="delivery-address">
        <text class="address-label">📍 送达地址：</text>
        <text class="address-text">{{ orderInfo.deliveryAddress }}</text>
      </view>
    </view>

    <!-- 地图容器 -->
    <view v-if="markers.length" class="map-container">
      <view class="map-title">
        <text class="map-title-text">📍 运输轨迹</text>
      </view>
      <map
          :latitude="markers[0].latitude"
          :longitude="markers[0].longitude"
          :markers="markers"
          :polyline="polyline"
          class="express-map"
          :show-location="false"
          :enable-3D="true"
          :enable-overlooking="true"
          :enable-zoom="true"
          :enable-scroll="true"
          :enable-rotate="false"
          :enable-satellite="false"
      ></map>
    </view>

    <!-- 物流跟踪时间线 -->
    <view v-if="expressInfo" class="timeline-container">
      <view class="timeline-title">
        <text class="timeline-title-text">🕒 物流跟踪</text>
        <text class="timeline-count">{{ expressInfo.data.length }} 条记录</text>
      </view>

      <view class="timeline-list">
        <view
            class="timeline-item"
            v-for="(item, idx) in expressInfo.data"
            :key="idx"
            :class="{ 'is-latest': idx === 0 }"
        >
          <view class="timeline-marker">
            <view class="timeline-dot" :class="{ 'is-active': idx === 0 }"></view>
            <view v-if="idx !== expressInfo.data.length - 1" class="timeline-line"></view>
          </view>

          <view class="timeline-content">
            <view class="timeline-card" :class="{ 'is-latest': idx === 0 }">
              <view class="timeline-header">
                <text class="timeline-time">{{ item.time }}</text>
                <view v-if="idx === 0" class="latest-badge">最新</view>
              </view>
              <text class="timeline-desc">{{ item.context }}</text>
              <view v-if="item.areaName" class="timeline-location">
                <text class="location-icon">📍</text>
                <text class="location-text">{{ item.areaName }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <text class="empty-icon">📦</text>
      <text class="empty-text">暂无物流信息</text>
      <text class="empty-desc">请稍后再试或联系客服</text>
    </view>
  </view>
</template>

<style scoped>
.express-wrap {
  padding: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  padding-bottom: 40rpx;
}

/* 状态卡片 */
.status-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 0 0 40rpx 40rpx;
  padding: 60rpx 32rpx 32rpx 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.status-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.status-icon {
  font-size: 48rpx;
  margin-right: 20rpx;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  border-radius: 50%;
  color: #fff;
}

.status-text {
  flex: 1;
}

.status-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 8rpx;
}

.status-subtitle {
  font-size: 26rpx;
  color: #6b7280;
}

.express-number {
  font-size: 24rpx;
  color: #6b7280;
  background: #f9fafb;
  padding: 16rpx 20rpx;
  border-radius: 16rpx;
  border-left: 4rpx solid #6366f1;
  margin-bottom: 16rpx;
}

.delivery-address {
  font-size: 24rpx;
  color: #374151;
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.05), rgba(139, 92, 246, 0.05));
  padding: 16rpx 20rpx;
  border-radius: 16rpx;
  border-left: 4rpx solid #10b981;
}

.address-label {
  color: #10b981;
  font-weight: bold;
}

.address-text {
  color: #374151;
  font-weight: 500;
}

/* 地图容器 */
.map-container {
  margin: 0 24rpx 24rpx 24rpx;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.map-title {
  padding: 24rpx 24rpx 16rpx 24rpx;
  background: linear-gradient(135deg, #f8fafc, #e2e8f0);
}

.map-title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #374151;
}

.express-map {
  width: 100%;
  height: 400rpx;
}

/* 时间线容器 */
.timeline-container {
  margin: 0 24rpx;
  background: #fff;
  border-radius: 24rpx;
  padding: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.timeline-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f1f5f9;
}

.timeline-title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #374151;
}

.timeline-count {
  font-size: 22rpx;
  color: #6b7280;
  background: #f1f5f9;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.timeline-list {
  position: relative;
}

.timeline-item {
  display: flex;
  margin-bottom: 24rpx;
  position: relative;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

.timeline-marker {
  position: relative;
  margin-right: 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.timeline-dot {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background: #d1d5db;
  border: 4rpx solid #fff;
  box-shadow: 0 0 0 2rpx #d1d5db;
  z-index: 2;
}

.timeline-dot.is-active {
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  box-shadow: 0 0 0 2rpx #6366f1, 0 0 20rpx rgba(99, 102, 241, 0.3);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.timeline-line {
  width: 2rpx;
  background: linear-gradient(to bottom, #d1d5db, transparent);
  flex: 1;
  margin-top: 8rpx;
}

.timeline-content {
  flex: 1;
}

.timeline-card {
  background: #f8fafc;
  border-radius: 16rpx;
  padding: 20rpx;
  border-left: 4rpx solid #e5e7eb;
  transition: all 0.3s ease;
}

.timeline-card.is-latest {
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.05), rgba(139, 92, 246, 0.05));
  border-left-color: #6366f1;
  box-shadow: 0 4rpx 20rpx rgba(99, 102, 241, 0.1);
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.timeline-time {
  font-size: 24rpx;
  color: #6b7280;
  font-weight: 500;
}

.latest-badge {
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-weight: bold;
}

.timeline-desc {
  font-size: 28rpx;
  color: #374151;
  line-height: 1.6;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.timeline-location {
  display: flex;
  align-items: center;
  background: rgba(59, 130, 246, 0.1);
  padding: 8rpx 12rpx;
  border-radius: 12rpx;
  margin-top: 8rpx;
}

.location-icon {
  font-size: 20rpx;
  margin-right: 8rpx;
}

.location-text {
  font-size: 24rpx;
  color: #3b82f6;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 24rpx;
  margin: 120rpx 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 24rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #374151;
  font-weight: bold;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #6b7280;
}
</style>
